import {getDetail} from '@/api/user';
import type {IUser} from '@/typings/interface';
import {delayNavigateTo} from '@/utils/navigator';

export const useUser = defineStore(
    'user',
    () => {
        let isLogin = $ref<boolean>(false);
        let token = $ref<string>('');
        let details = $ref<IUser>();

        // 更改登录状态
        async function switchLoginState(_token: string) {
            token = _token;
            isLogin = true;
            await syncUserInfo();
            delayNavigateTo('/pages/index/index');
        }

        // 获取用户信息
        async function syncUserInfo() {
            if (!token || !isLogin) return;
            details = (await getDetail()).data;
        }

        // 退出登录
        function logout() {
            token = '';
            isLogin = false;
            details = {} as any;
        }

        return $$({
            isLogin,
            token,
            switchLoginState,
            syncUserInfo,
            details,
            logout,
        });
    },
    {persist: true}
);

